package com.gonsin.gview.common.auth;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.gonsin.base.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api(tags = "鉴权相关接口")
@ApiSupport(order = 1)
public class TokenController {

    @Autowired private JwtConfig jwtConfig;


    /**
     * 获取token
     * @return
     */
    @Deprecated
    @ApiOperation("TOKEN - 获取token")
    @PostMapping("/api/base/token")
    public ResponseResult<TokenBo> getToken(){
        Map<String, Object> payload = new HashMap<>();
        payload.put(AuthCommon.SESSION_ID, RandomStringUtils.random(32, true, true));
        Algorithm algorithm = Algorithm.HMAC256(jwtConfig.getJwtSecret());
        long expiredTime = System.currentTimeMillis() + jwtConfig.getExpiredTime();
        String token = JWT.create()
                .withIssuer(AuthCommon.ISSUER)
                .withIssuedAt(new Date())
                .withPayload(payload)
                // 设置真实的过期时间延后60秒，防止边界问题
                .withExpiresAt(new Date(expiredTime + 60000))
                .sign(algorithm);
        return ResponseResult.result(new TokenBo(token, expiredTime));
    }


    /**
     * 获取token
     * @return
     */
    @ApiOperation("TOKEN - 刷新token")
    @PostMapping("/api/base/token/refresh")
    public ResponseResult<TokenBo> refreshToken(@ApiIgnore HttpServletRequest request){

        String lastToken = request.getHeader(AuthCommon.TOKEN);


        Algorithm algorithm = Algorithm.HMAC256(jwtConfig.getJwtSecret());
        JWTVerifier verifier = JWT.require(algorithm)
                .withIssuer(AuthCommon.ISSUER)
                .build(); //Reusable verifier instance
        DecodedJWT jwt = verifier.verify(lastToken);
//        String sessionId = jwt.getClaim(AuthCommon.SESSION_ID).asString();
        Map<String, Claim> payload = jwt.getClaims();


//        Map<String, Object> payload = new HashMap<>();
//        payload.put(AuthCommon.SESSION_ID, sessionId);
        algorithm = Algorithm.HMAC256(jwtConfig.getJwtSecret());
        long expiredTime = System.currentTimeMillis() + jwtConfig.getExpiredTime();
        String token = JWT.create()
                .withIssuer(AuthCommon.ISSUER)
                .withIssuedAt(new Date())
                .withPayload(payload)
                .withExpiresAt(new Date(expiredTime))
                .sign(algorithm);
        return ResponseResult.result(new TokenBo(token, expiredTime));
    }


    /**
     * 获取token
     * @return
     */
    @ApiOperation("TOKEN - 获取token中session的内容")
    @ApiOperationSupport
    @PostMapping("/api/base/token/session")
    public ResponseResult<Map<String, Object>> getSession(@ApiIgnore HttpServletRequest request){
        HttpSession session = request.getSession();
        Enumeration<String> keys = session.getAttributeNames();
        Map<String, Object> sessionContent = new HashMap<>();
        while(keys.hasMoreElements()){
            String value = keys.nextElement();
            sessionContent.put(value, session.getAttribute(value));
        }
        return ResponseResult.result(sessionContent);
    }

}
